

import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pleasure_video/api/api_common.dart';
import 'package:flutter_pleasure_video/api/yck_mumuceo_com_api.dart';
import 'package:flutter_pleasure_video/constant/color.dart';
import 'package:flutter_pleasure_video/constant/style.dart';
import 'package:flutter_pleasure_video/util/screen_util.dart';
import 'package:flutter_pleasure_video/util/string_util.dart';
import 'package:flutter_pleasure_video/widget/common/custom_appbar.dart';
import 'package:flutter_pleasure_video/util/extensions/string_extensions.dart';
import 'package:get/get.dart';
import 'package:loading/indicator/ball_pulse_indicator.dart';
import 'package:loading/loading.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';


// ignore: must_be_immutable
class ScanQRCodePage extends StatelessWidget {
  bool upOrDown = false;
  int? timeStamp;
  Barcode? result;
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  bool requestOver = true;
  UpOrDownController upOrDownController=UpOrDownController();
  LoadingController _loadingController=LoadingController();
  bool isFirst=true;


  void _onQRViewCreated(QRViewController controller) {
    controller.scannedDataStream.listen((scanData) {
      if(!requestOver){
        return;
      }
      if(timeStamp==null){
        timeStamp = DateTime.now().millisecondsSinceEpoch;
        resolveScanResult(scanData.code);
      }
      if(DateTime.now().millisecondsSinceEpoch-timeStamp!>2000){
        timeStamp =DateTime.now().millisecondsSinceEpoch;
        resolveScanResult(scanData.code);
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        titleString: "扫描二维码",
        leadingOnTap: () {
          Navigator.pop(context);
        },
        actions: [
          CustomAppBarTextButton("相册", AppColor.textPrimary2, () {
            // _getImagePicker();
          }),
        ],
      ),
      body: Stack(
        children: [
          Container(
              width: ScreenUtil.instance.screenWidthDp,
              height: ScreenUtil.instance.height,
              child: QRView(
                key: qrKey,
                onQRViewCreated: _onQRViewCreated,
              )
          ),
          _scanCoverView(),
          Obx(
            ()=>Visibility(
              visible: _loadingController.visible.value,
              child: Container(
                width: ScreenUtil.instance.width,
                height: ScreenUtil.instance.height,
                color: AppColor.mainBlue.withOpacity(0.4),
                child: UnconstrainedBox(
                  alignment: Alignment.topCenter,
                  child: Container(
                    margin: EdgeInsets.only(top: ScreenUtil.instance.height * 0.24+125-25),
                    height: 50,
                    width: 50,
                    child: Loading(indicator: BallPulseIndicator(), size: 50.0),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _scanCoverView() {
    return Stack(
      children: [
        Container(
          height: ScreenUtil.instance.height,
          width: ScreenUtil.instance.screenWidthDp,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                height: ScreenUtil.instance.height * 0.24,
                width: ScreenUtil.instance.screenWidthDp,
                color: AppColor.black.withOpacity(0.3),
              ),
              SizedBox(
                height: 250,
              ),
              Expanded(
                child: Container(
                  color: AppColor.black.withOpacity(0.3),
                ),
              ),
            ],
          ),
        ),
        _textContainerColumn()
      ],
    );
  }

  Widget _textContainerColumn() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            height: ScreenUtil.instance.height * 0.24,
          ),
          Row(
            children: [
              Expanded(
                child: Container(
                  height: 250,
                  color: AppColor.black.withOpacity(0.3),
                ),
              ),
              _animationContainer(),
              Expanded(
                child: Container(
                  height: 250,
                  color: AppColor.black.withOpacity(0.3),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 12,
          ),
          Text(
            "将二维码放入框内，即可自动扫描",
            style: AppStyle.whiteMedium14,
          ),
          SizedBox(
            height: 48,
          ),Container(),
          SizedBox(
            height: 9,
          ), Container()
        ],
      ),
    );
  }

  Widget _whiteSmallRow() {
    return Container(
      width: 26,
      height: 4,
      color: AppColor.white,
    );
  }

  Widget _whiteSmallColumn() {
    return Container(
      width: 4,
      height: 26,
      color: AppColor.white,
    );
  }

  Widget _animationContainer() {
    return Container(
        width: 250,
        height: 250,
        child: Stack(
          children: [
            Positioned(top: 0, left: 0, child: _whiteSmallRow()),
            Positioned(top: 0, left: 0, child: _whiteSmallColumn()),
            Positioned(top: 0, right: 0, child: _whiteSmallRow()),
            Positioned(top: 0, right: 0, child: _whiteSmallColumn()),
            Positioned(bottom: 0, left: 0, child: _whiteSmallRow()),
            Positioned(bottom: 0, left: 0, child: _whiteSmallColumn()),
            Positioned(bottom: 0, right: 0, child: _whiteSmallRow()),
            Positioned(bottom: 0, right: 0, child: _whiteSmallColumn()),

            Obx(
              (){
                if(isFirst){
                  isFirst=false;
                  Future.delayed(Duration(milliseconds: 100),(){
                    upOrDownController.setUpOrDown(!upOrDownController.upOrDown.value);
                  });
                }
                var marginTopValue= upOrDownController.upOrDown.value?250:0;
                return AnimatedContainer(
                  duration: Duration(milliseconds:  marginTopValue==0?100:3000),
                  margin: EdgeInsets.only(top: upOrDownController.upOrDown.value?250:0),
                  onEnd: () {
                    upOrDownController.setUpOrDown(!upOrDownController.upOrDown.value);
                  },
                  child: Container(
                    width: 250,
                    height: 2,
                    color: marginTopValue==0?AppColor.transparent:AppColor.white,
                  ),
                );
              }
            ),
          ],
        ));
  }



  //解析扫出来的值
  void resolveScanResult(String result) async {
    requestOver=false;
    "result:$result".print;
    if(StringIsURLUtil.isURL(result)){
      _loadingController.setVisible(true);
      if(result.contains(YckMumuceoComApi.httpUrl)){
        YckMumuceoComApi.getYckRuleList(result).then((result)=>Get.back(result: result));
      }else {
        ApiCommon.requestGetUrl(result).then((result) => Get.back(result: result));
      }
    }else {
      Get.back(result: result);
    }
  }

}

class UpOrDownController extends GetxController{
  var upOrDown=false.obs;

  setUpOrDown(bool isUpOrDown)=>this.upOrDown.value=isUpOrDown;
}
class LoadingController extends GetxController{
  var visible=false.obs;

  setVisible(bool visible)=>this.visible.value=visible;
}

